/*
 * Copyright (C) 2011, EADS France
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 */

package xowl.interpreter.impl;

import java.util.ArrayList;
import java.util.List;
import xowl.interpreter.XOWLException;

/**
 *
 * @author Laurent WOUTERS
 */
public class StatementAssignRunner extends StatementRunner {
    private xowl.lang.actions.Assign statement;

    public StatementAssignRunner(xowl.lang.actions.Assign statement, ThreadRunner runner) {
        super(runner);
        this.statement = statement;
    }

    @Override public String getFile() { return statement.getFile(); }
    @Override public int getLine() { return statement.getLine(); }
    @Override public void execute() throws XOWLException {
        xowl.lang.actions.CodeVariable var = statement.getVariable();
        List<Integer> indices = new ArrayList<Integer>();
        if (statement.getLiteralSeq() != null) {
            for (xowl.lang.owl2.LiteralExpression litExp : xowl.interpreter.impl.Sequences.toExpressionList(statement.getLiteralSeq())) {
                Integer index = Integer.parseInt(runner.evaluator.evalLiteral(runner.evaluator, litExp).getLexicalValue());
                indices.add(index);
            }
        }
        xowl.lang.runtime.Value value = runner.evaluator.evaluate(runner.evaluator, statement.getExpressionAs(null));
        if (indices.isEmpty())
            runner.assign(var, value);
        else {
            xowl.lang.runtime.Array array = runner.evaluator.evalArray(runner.evaluator, var);
            for (int i=0; i!=indices.size() - 1; i++)
                array = (xowl.lang.runtime.Array)array.getAllElements().toArray()[indices.get(i)];
            for (xowl.lang.runtime.Element elem : array.getAllElements()) {
                if (elem.getIndex().equals(indices.get(indices.size() - 1))) {
                    elem.setValue(value);
                    break;
                }
            }
        }
        runner.statementPop();
    }
    @Override public boolean onBreak() { return true; }
}
